﻿using System;
using System.Threading;
using System.Windows;

namespace ControleRepresentante.Migration
{
    public partial class MainWindow
    {
        private Migrator m_Migrator;
        private Timer m_Timer;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Start(object sender, RoutedEventArgs e)
        {
            m_Migrator = new Migrator();
            m_Migrator.End += MigratorEnd;
            m_Migrator.Start();
            start.Visibility = Visibility.Collapsed;
            cancel.Visibility = Visibility.Visible;
            SetTimer();
        }

        void MigratorEnd(object sender, EventArgs e)
        {
            Dispatcher.Invoke((Action) (() =>
            {
                cancel.Visibility = Visibility.Collapsed;
                m_Timer.Dispose();
            }));
        }

        private void OnTimerTick(object o)
        {
            Dispatcher.Invoke((Action)(() =>
            {
                MigrationStatus migrationStatus = m_Migrator.MigrationStatus;
                currentStep.Text = migrationStatus.CurrentStep;
                currentStepProgress.Text = migrationStatus.CurrentStepProgress.ToString();
                estimatedTime.Text = migrationStatus.EstimatedTime.ToString();
                progression.Value = migrationStatus.CurrentStepProgress;
                currentItem.Text = migrationStatus.CurrentIndex.ToString();
                totalItems.Text = migrationStatus.Total.ToString();
                SetTimer();
            }));
        }

        private void SetTimer()
        {
            if (m_Timer != null)
            {
                m_Timer.Dispose();
            }
            m_Timer = new Timer(OnTimerTick, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
        }

        private void CancelMigration(object sender, RoutedEventArgs e)
        {
            m_Migrator.Cancel();
        }
    }
}
